package com.apache.tools;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.Properties;

/**
 * 
 * description:  
 * @author Hou DaYu 创建时间：2014-7-15  
 * @Copyright(c)2014:
 */
public class OsUtils {
	public static final boolean IS_MAC = "Mac OS X".equals(System.getProperty("os.name"));
	public static final boolean IS_WINDOWS = System.getProperty("os.name").contains("Windows");
	public static final boolean IS_LINUX = System.getProperty("os.name").toLowerCase().contains("linux");

	public static void removeProxySettingsIfMac() {
		// Stupid Safari will only proxy with the
		// OS level Network Proxy settings.
		// We don't want them so nuke them here.
		if (OsUtils.IS_MAC) {
			Properties props = System.getProperties();
			props.remove("http.proxyPort");
			props.remove("http.proxyHost");
			props.remove("https.proxyPort");
			props.remove("https.proxyHost");
		}
	}

	/**  
	 * 获取本机ip地址  
	 * 
	 * @return 返回本机的IP地址
	 */
	public static String getLocalIp() {
		String localIp = null;
		try {
			if ("linux".equals(OsUtils.getSystemType())) {
				localIp = getLinuxIP();
			} else {
				localIp = InetAddress.getLocalHost().getHostAddress();
			}
		} catch (Exception e) {
			return "127.0.0.1";
		}
		return localIp;
	}

	/**
	 * 获取操作系统类型
	 *
	 * @return 返回操作系统类型
	 */
	public static String getSystemType() {
		String result = "windows";
		if (System.getProperty("os.name").equals("Linux")) {
			result = "linux";
		} else if ("Mac OS X".equals(System.getProperty("os.name"))) {
			result = "Mac OS X";
		}
		return result;
	}

	public static String getWindowsMACAddress() {
		String address = "";
		try {
			ProcessBuilder pb = new ProcessBuilder("ipconfig", "/all");
			Process p = pb.start();
			BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
			String line;
			while ((line = br.readLine()) != null) {
				if (line.indexOf("Physical Address") != -1) {
					int index = line.indexOf(":");
					address = line.substring(index + 1);
					break;
				}
			}
			br.close();
			return address.trim();
		} catch (IOException e) {
		}
		return address;
	}

	public static String getLinuxMACAddress() {
		String address = "";
		try {
			ProcessBuilder pb = new ProcessBuilder("ifconfig", "-a");
			Process p = pb.start();
			BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
			String line;
			while ((line = br.readLine()) != null) {
				System.out.println(line);
				if (line.indexOf("Link encap:Ethernet    HWaddr") != -1) {
					int index = line.indexOf("HWaddr");
					address = line.substring(index + 7);
					break;
				}
			}
			br.close();
			return address.trim();
		} catch (IOException e) {
		}
		return address;
	}

	public static String getMACAddress() {
		String address = "";
		String os = getSystemType();
		if (os != null && os.startsWith("windows")) {
			address = getWindowsMACAddress();
		} else {
			address = getLinuxMACAddress();
		}
		return address;
	}

	private static String getLinuxIP() {
		String localIp = "127.0.0.1";
		Enumeration<NetworkInterface> netInterfaces = null;
		try {
			netInterfaces = NetworkInterface.getNetworkInterfaces();

			while (netInterfaces.hasMoreElements()) {

				NetworkInterface ni = netInterfaces.nextElement();
				String name = ni.getName();
				Enumeration<InetAddress> ips = ni.getInetAddresses();
				while (ips.hasMoreElements()) {
					String Ip = ((InetAddress) ips.nextElement()).getHostAddress();
					if (!"127.0.0.1".equals(Ip) && ("eth0".equalsIgnoreCase(name) || "eth1".equalsIgnoreCase(name))
							&& Ip.indexOf(":") == -1) {
						localIp = Ip;
						break;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return localIp;
	}

	//获取MAC地址的方法  
	public static String getMacAddress() throws Exception {
		InetAddress ia = InetAddress.getLocalHost();//获取本地IP对象 
		//获得网络接口对象（即网卡），并得到mac地址，mac地址存在于一个byte数组中。  
		byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
		//下面代码是把mac地址拼装成String  
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < mac.length; i++) {
			if (i != 0) {
				sb.append("-");
			}
			//mac[i] & 0xFF 是为了把byte转化为正整数  
			String s = Integer.toHexString(mac[i] & 0xFF);
			sb.append(s.length() == 1 ? 0 + s : s);
		}
		//把字符串所有小写字母改为大写成为正规的mac地址并返回  
		return sb.toString().toUpperCase();
	}
}
